package services;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpServlet;

import models.UserModel;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import entities.Article;
import entities.SubmitSite;
import entities.User;

import admin.models.ArticleModel;
import admin.models.SubmitSiteModel;

public class SendArticleTranslateService extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		ArticleModel articleModel = ArticleModel.getInstance();
		Article article = articleModel.getArticle(id);
		
		if (article != null) {
			
			String website = article.getWebsite();
			String name = article.getAuthorName();
			String email = article.getEmail();
			
			if (!article.getCreator().isEmpty()) {
				UserModel userModel = UserModel.getInstance();
				User author = userModel.getUser(article.getCreator());
				if (author != null) {
					website = author.getWebsite();
					name = author.getName();
					email = author.getUsername();
				}
			}
			
			
			SubmitSiteModel submitSiteModel = SubmitSiteModel.getInstance();
			List<SubmitSite> sites = submitSiteModel.getSiteActive();
			
			for (SubmitSite site : sites) {
				try {
					Connection conn = Jsoup.connect(site.getSiteUrl());
					Document doc = conn
						.header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
						.header("accept-Language", "en-us,en;q=0.5")
						.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1")
						.data("post[title]", article.getTitle())
						.data("post[content]", article.getContent())
						.data("post[category]",article.getCategory())
						.data("post[name]",name)
						.data("post[email]",email)
						.data("post[website]", website)
						.data("post[keywords]",article.getTags())
						.data("post[sl]", site.getSl())
						.data("post[tl]", site.getTl())
						.followRedirects(false)
						.post();
				} catch (Exception e) {
					// TODO: handle exception
				}
				
			}
		}
	}
}
